package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 计算热文章
     */
    @Override
    public void computeHotArticle() {
        //查询前5天（已上架且未删除文章数据）
        String date = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> articleList = apArticleMapper.selectList(
                Wrappers.<ApArticle>lambdaQuery()
                        .gt(ApArticle::getPublishTime, date)
        );

        //计算热点文章分值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(articleList);

        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 将每个频道分数高的前30三十条文章加入redis缓存
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //查询频道列表
        ResponseResult result = adminFeign.selectAllChannel();
        if (result.getCode()==0){
            //解析返回数据
            List<AdChannel> channelList = JSON.parseArray(JSON.toJSONString(result.getData()), AdChannel.class);
            channelList.forEach(adChannel -> {
                //遍历热点集合****(加入缓存同时排序)
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                        .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(adChannel.getId()))
                        .collect(Collectors.toList());
                //给每个频道加入三十条热点
                sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            });
            //给推荐频道加30条热点
            sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
        }
    }

    /**
     * 文章加入缓存方法
     * @param hotArticleVos
     * @param s
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String s) {
        //排序 并且设置30条限制******************limit方法
        List<HotArticleVo> articleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        redisTemplate.opsForValue().set(s,JSON.toJSONString(articleVos));

        System.out.println("***********************************redis缓存成功*************************");
    }

    /**
     * 计算热点文章的分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();

        //遍历查询到的文章，计算分值
        for (ApArticle article : articleList) {
            HotArticleVo hotArticleVo=new HotArticleVo();
            BeanUtils.copyProperties(article,hotArticleVo);
            Integer score=computeScore(article);
            hotArticleVo.setScore(score);
            hotArticleVoList.add(hotArticleVo);
        }
        return hotArticleVoList;
    }

    /**
     * 分数计算
     * @param article
     * @return
     */
    private Integer computeScore(ApArticle article) {
        int score = 0;
        // 阅读 1
        if (article.getViews() != null) {
            score += article.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 3
        if (article.getLikes() != null) {
            score += article.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (article.getComment() != null) {
            score += article.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (article.getCollection() != null) {
            score += article.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}